import pygame
import sys
import os
from typing import List
from .button import Button
from .music_player import MusicPlayer
import random

# 添加父目录到系统路径
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)

from constant import Setting


class BattlePopup:
    """战斗结果弹窗类"""
    def __init__(self, settings, winner, screen):
        self.settings = settings
        self.winner = winner
        self.screen = screen
        self.running = True
        
        # 弹窗尺寸和位置
        self.width = 600
        self.height = 250
        self.x = (self.settings.screen_width - self.width) // 2
        self.y = (self.settings.screen_height - self.height) // 2
        self.rect = pygame.Rect(self.x, self.y, self.width, self.height)
        
        # 颜色设置
        self.bg_color = (50, 50, 50, 230)  # 半透明深色背景
        self.border_color = (255, 215, 0)  # 金色边框
        self.text_color = (255, 255, 255)  # 白色文字
        
        # 字体设置
        self.title_font = pygame.font.SysFont("SimHei", 36, bold=True)
        self.message_font = pygame.font.SysFont("SimHei", 24)
        self.button_font = pygame.font.SysFont("SimHei", 20, bold=True)
        
        # 创建确认按钮
        self.ok_button = Button(
            x=self.x + self.width // 2 - 75,
            y=self.y + self.height - 60,
            width=150,
            height=40,
            text="continue",
            settings=settings,
            action=self.close
        )
        
        # 准备文本内容
        self._prepare_text()
    
    def _prepare_text(self):
        """准备弹窗文本内容"""
        if self.winner == "player":
            self.title = "WIN！"
            self.message = "YOU WIN！A new treasure is waiting for you to claim."
            self.title_color = (0, 255, 0)  # 绿色
        else:
            self.title = "FAIL"
            self.message = "You lose this war in ChangAn"
            self.title_color = (255, 0, 0)  # 红色
    
    def close(self):
        """关闭弹窗"""
        self.running = False
    
    def handle_events(self):
        """处理弹窗事件"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
                # 退出整个游戏
                pygame.quit()
                sys.exit()
            self.ok_button.handle_event(event)
    
    def draw(self):
        """绘制弹窗"""
        # 绘制半透明背景遮罩
        overlay = pygame.Surface((self.settings.screen_width, self.settings.screen_height), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 150))
        self.screen.blit(overlay, (0, 0))
        
        # 绘制弹窗背景
        pygame.draw.rect(self.screen, self.bg_color, self.rect, border_radius=10)
        pygame.draw.rect(self.screen, self.border_color, self.rect, 3, border_radius=10)
        
        # 绘制标题
        title_surf = self.title_font.render(self.title, True, self.title_color)
        title_rect = title_surf.get_rect(center=(self.x + self.width // 2, self.y + 50))
        self.screen.blit(title_surf, title_rect)
        
        # 绘制消息
        message_surf = self.message_font.render(self.message, True, self.text_color)
        message_rect = message_surf.get_rect(center=(self.x + self.width // 2, self.y + 110))
        self.screen.blit(message_surf, message_rect)
        
        # 绘制按钮
        self.ok_button.draw(self.screen)
        
        pygame.display.flip()
    
    def run(self):
        """弹窗主循环"""
        clock = pygame.time.Clock()
        while self.running:
            clock.tick(self.settings.fps)
            self.handle_events()
            self.draw()

class BattleUI:
    """战斗界面类（技能显示改为PP形式）"""
    def __init__(self, player, enemy, battle):
        pygame.init()
        self.settings = Setting()
        self.root_dir = parent_dir

        # 屏幕设置
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height)
        )
        pygame.display.set_caption(f"{self.settings.screen_title} - Battle")

        # 战斗日志相关设置
        self.battle_log = []  # 存储战斗日志
        self.log_box_width = 250  # 日志框宽度
        self.log_box_height = 150  # 日志框高度
        self.log_box_x = 20  # 左侧距离
        self.log_box_y = 20  # 顶部距离
        self.log_line_height = 25  # 每行日志高度
        self.log_font = pygame.font.SysFont("SimHei", 18)  # 日志字体
        #战斗实例化
        self.battle = battle
        self.battle_log = self.battle.battle_log
        

        # 角色数据
        self.player = player
        self.enemy = enemy

        # 先定义布局属性，再加载资源
        self.skill_area_height = 180    # 技能区高度（紧凑化）
        self.role_center_offset = 350  # 角色距屏幕中心的水平偏移
        self.status_follow_role = True  # 血条跟随角色位置
        self.status_bar_size = (200, 25) # 血条尺寸

        # 加载核心资源
        self.background = self._load_background()
        self.player_image = self._load_character_image(player.image_path)
        self.enemy_image = self._load_character_image(enemy.image_path)
        self.bottom_bg_image = self._load_bottom_bg_image()
        
        # 加载受击特效图片和闪烁效果
        self.hit_effect_image = self._load_hit_effect_image()
        self.player_hit = False  # 玩家受击状态
        self.enemy_hit = False   # 敌人受击状态
        self.hit_effect_duration = 15  # 受击特效显示帧数
        self.player_hit_timer = 0      # 玩家受击计时器
        self.enemy_hit_timer = 0       # 敌人受击计时器
        
        # 闪烁效果参数 - 修改为透明效果
        self.player_flash = False
        self.enemy_flash = False
        self.player_flash_timer = 0
        self.enemy_flash_timer = 0
        self.flash_interval = 3  # 闪烁间隔帧数
        self.flash_alpha = 100  # 透明效果的透明度值（0-255）

        # 震动效果状态 - 增强版（增加敌人震动）
        self.player_shake = False
        self.enemy_shake = False
        self.shake_count = 0
        self.shake_range = 8  # 增大震动范围
        self.shake_intensity = [5, 8, 6, 3, 5, 2, 4, 1]  # 震动强度变化序列
        self.enemy_shake_intensity = [6, 9, 7, 4, 6, 3, 5, 2]  # 敌人震动强度（更强）
        
        # 伤害数字显示
        self.damage_numbers = []  # 存储伤害数字信息：(x, y, text, timer, color)

        # 创建技能按钮
        self.skill_buttons = self._create_skill_buttons()
        #music_player
        self.music_player = MusicPlayer()
        # 状态控制
        self.running = True

    def _load_hit_effect_image(self):
        """加载受击特效图片"""
        try:
            hit_effect_path = os.path.join(
                self.root_dir, self.settings.images_path["hit_effect"]
            )
            effect = pygame.image.load(hit_effect_path).convert_alpha()
            # 调整特效图片大小为角色的80%
            target_size = (int(250 * 0.8), int(280 * 0.8))
            return pygame.transform.scale(effect, target_size)
        except FileNotFoundError:
            print(f"【错误】未找到受击特效图片: {hit_effect_path}")
            # 创建一个红色闪烁的 fallback 特效
            target_size = (200, 224)
            fallback_surf = pygame.Surface(target_size, pygame.SRCALPHA)
            pygame.draw.circle(fallback_surf, (255, 0, 0, 180), (target_size[0]//2, target_size[1]//2), target_size[0]//2)
            return fallback_surf

    def _load_background(self):
        """加载战斗主背景图"""
        try:
            bg_path = os.path.join(
                self.root_dir, self.settings.images_path["battle_background"]
            )
            background = pygame.image.load(bg_path).convert()
            return pygame.transform.scale(
                background, (self.settings.screen_width, self.settings.screen_height)
            )
        except FileNotFoundError:
            print(f"【错误】未找到战斗背景图: {bg_path}")
            fallback_surf = pygame.Surface(
                (self.settings.screen_width, self.settings.screen_height)
            )
            fallback_surf.fill(self.settings.bg_path_battle)
            return fallback_surf

    def _load_character_image(self, image_path):
        """加载角色图片（适中尺寸）"""
        try:
            full_path = os.path.join(self.root_dir, image_path)
            img = pygame.image.load(full_path).convert_alpha()
            target_size = (250, 280)  # 比原图稍小，更紧凑
            return pygame.transform.scale(img, target_size)
        except FileNotFoundError:
            print(f"【错误】未找到角色图片: {full_path}")
            target_size = (250, 280)
            fallback_surf = pygame.Surface(target_size, pygame.SRCALPHA)
            fallback_surf.fill((100, 100, 100, 200))
            return fallback_surf

    def _load_bottom_bg_image(self):
        """加载底部技能区背景（更紧凑）"""
        try:
            bottom_bg_path = os.path.join(
                self.root_dir, self.settings.title_images_path["select_title"]
            )
            bottom_bg = pygame.image.load(bottom_bg_path).convert_alpha()

            # 底部区域高度=技能区高度
            target_width = self.settings.screen_width
            target_height = self.skill_area_height
            scale_width = target_width / bottom_bg.get_width()
            scale_height = target_height / bottom_bg.get_height()
            scale_ratio = max(scale_width, scale_height)

            # 缩放并裁剪图片
            scaled_width = int(bottom_bg.get_width() * scale_ratio)
            scaled_height = int(bottom_bg.get_height() * scale_ratio)
            scaled_bg = pygame.transform.scale(bottom_bg, (scaled_width, scaled_height))

            crop_x = max(0, (scaled_width - target_width) // 2)
            crop_y = max(0, (scaled_height - target_height) // 2)
            crop_width = min(target_width, scaled_width - crop_x)
            crop_height = min(target_height, scaled_height - crop_y)
            crop_rect = pygame.Rect(crop_x, crop_y, crop_width, crop_height)
            final_bg = scaled_bg.subsurface(crop_rect).copy()

            # 补全不足尺寸
            if final_bg.get_width() < target_width or final_bg.get_height() < target_height:
                full_bg = pygame.Surface((target_width, target_height), pygame.SRCALPHA)
                edge_color = final_bg.get_at((0, 0))
                full_bg.fill(edge_color)
                full_bg.blit(final_bg, (
                    (target_width - final_bg.get_width()) // 2,
                    (target_height - final_bg.get_height()) // 2
                ))
                final_bg = full_bg

            return final_bg
        except FileNotFoundError:
            print(f"【错误】未找到底部背景图: {bottom_bg_path}")
            fallback_surf = pygame.Surface(
                (self.settings.screen_width, self.skill_area_height),
                pygame.SRCALPHA
            )
            fallback_surf.fill((50, 100, 200, 200))  # 蓝色半透明 fallback
            return fallback_surf

    def _create_skill_buttons(self):
        """创建技能按钮（显示PP形式）"""
        skill_buttons = []
        # 技能区居中，按钮更紧凑
        menu_width = int(self.settings.screen_width * 0.8)  # 占屏幕80%宽度
        menu_height = self.skill_area_height - 30  # 减去边距
        menu_left = (self.settings.screen_width - menu_width) // 2
        menu_top = self.settings.screen_height - self.skill_area_height + 15  # 顶部留15px边距
        menu_rect = pygame.Rect(menu_left, menu_top, menu_width, menu_height)

        # 按钮尺寸缩小，间距减小
        btn_width = 260
        btn_height = 150
        btn_spacing = (menu_rect.width - 4 * btn_width) // 5 # 5个间距

        btn_start_x = menu_rect.left + btn_spacing
        btn_y = menu_rect.top + (menu_rect.height - btn_height) // 2

        # 遍历主角技能，最多4个
        skills = self.player.skills_deck[:4]
        for i, skill in enumerate(skills):
            # 技能显示文本改为：技能名 PP 当前PP/MAX PP
            skill_text = f"{skill.name}\nPP {skill.current_pp}/{skill.max_pp}"
            btn_img_path = os.path.join(
                self.root_dir,
                self.settings.button_images_path["start_ui_button"]
            )
            btn_x = btn_start_x + i * (btn_width + btn_spacing)
            button = Button(
                x=btn_x,
                y=btn_y,
                width=btn_width,
                height=btn_height,
                text=skill_text,
                settings=self.settings,
                action=lambda s=skill: self._on_skill_click(s),
                image_path=btn_img_path
            )
            skill_buttons.append(button)

        # 添加逃跑按钮（在技能按钮右侧）
        escape_btn_x = btn_start_x + 4 * (btn_width + btn_spacing)
        escape_btn = Button(
            x=escape_btn_x,
            y=btn_y,
            width=btn_width,
            height=btn_height,
            text="escape",  # 逃跑按钮文本
            settings=self.settings,
            action=self._on_escape,  # 绑定逃跑事件
            image_path=os.path.join(self.root_dir, self.settings.button_images_path["start_ui_button"])
        )
        skill_buttons.append(escape_btn)  # 添加到按钮列表

        return skill_buttons

    # 添加逃跑按钮点击事件处理方法
    def _on_escape(self):
        """处理认输逻辑（改为改为输掉战斗）"""
        self.battle_log.append(f"{self.player.name}放弃了战斗！")
        self.battle.winner = self.enemy  # 设置敌人为胜利者
        self.battle.is_battle_over = True  # 标记战斗结束
        self.running = False  # 关闭战斗界面
        self.battle.end_battle("enemy")

    def _on_skill_click(self, skill):
        """技能点击事件（修正受击效果并添加延迟）"""
        skill_index = self.player.skills_deck.index(skill)
        # 检查PP是否足够使用技能
        if skill.current_pp <= 0:
            self.battle_log.append(f"{skill.name}的PP已耗尽！")
            return

        # 记录伤害值用于显示
        damage = 0
        if self.battle.player_turn("skill", skill_index):
            # 获取战斗造成的伤害
            if self.battle_log:
                last_log = self.battle_log[-1]
                if "造成了" in last_log and "点伤害" in last_log:
                    try:
                        damage = int(last_log.split("造成了")[1].split("点伤害")[0])
                    except:
                        damage = 0
            
            # 玩家攻击时的震动效果
            self.player_shake = True
            self.shake_count = len(self.shake_intensity)

            # 触发敌人受击效果（增加敌人震动）
            self.enemy_hit = True
            self.enemy_hit_timer = self.hit_effect_duration
            self.enemy_flash = True
            self.enemy_flash_timer = self.hit_effect_duration
            self.enemy_shake = True  # 触发敌人震动
            
            # 显示伤害数字
            if damage > 0:
                enemy_center = self._get_enemy_center()
                self.damage_numbers.append((
                    enemy_center[0], enemy_center[1] - 50,  # 位置在敌人上方
                    str(damage), 30, (255, 0, 0)  # 伤害值、显示时间、颜色
                ))

            # 更新技能按钮显示（PP减少）
            self.skill_buttons = self._create_skill_buttons()

            # # 添加回合延迟，让动画效果完整显示
            # self._round_delay(100)  # 延迟100毫秒

            if not self.battle.is_battle_over:
                # 敌人回合 - 增加延迟让玩家看清效果
                self._round_delay(100)

                # 敌人行动后触发玩家受击效果
                enemy_damage = 0
                    # 获取敌人造成的伤害
                if self.battle_log:
                    last_log = self.battle_log[-1]
                    if "造成了" in last_log and "点伤害" in last_log:
                        try:
                            enemy_damage = int(last_log.split("造成了")[1].split("点伤害")[0])
                        except:
                            enemy_damage = 0
                
                self.trigger_player_hit(enemy_damage)
                self._round_delay(100)

            if self.battle.is_battle_over:
                self.running = False

    def _round_delay(self, milliseconds):
        """回合延迟函数，让动画有足够时间显示"""
        start_time = pygame.time.get_ticks()
        while pygame.time.get_ticks() - start_time < milliseconds:
            # 延迟期间仍处理事件，避免程序假死
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.running = False
                    pygame.quit()
                    sys.exit()
            pygame.time.delay(10)  # 短暂延迟减少CPU占用

    def trigger_player_hit(self, damage=0):
        """触发玩家受击效果，增加伤害显示和受击特效"""
        self.player_hit = True
        self.player_hit_timer = self.hit_effect_duration  # 显示受击特效
        self.player_flash = True
        self.player_flash_timer = self.hit_effect_duration
        self.player_shake = True
        self.shake_count = len(self.shake_intensity)
        
        # 播放受击音效
        self.music_player.play_sound("hit")
        
        # 显示伤害数字
        if damage > 0:
            player_center = self._get_player_center()
            self.damage_numbers.append((
                player_center[0], player_center[1] - 50,  # 位置在玩家上方
                str(damage), 30, (255, 0, 0)  # 伤害值、显示时间、颜色
            ))

    # 在trigger_enemy_hit方法中添加音效播放
    def trigger_enemy_hit(self, damage=0):
        """触发敌人受击效果，增加伤害显示"""
        self.enemy_hit = True
        self.enemy_hit_timer = self.hit_effect_duration
        self.enemy_flash = True
        self.enemy_flash_timer = self.hit_effect_duration
        self.enemy_shake = True  # 触发敌人震动
        self.shake_count = len(self.enemy_shake_intensity)  # 使用敌人震动强度序列

        # 播放受击音效
        self.music_player.play_sound("hit")

        # 显示伤害数字
        if damage > 0:
            enemy_center = self._get_enemy_center()
            self.damage_numbers.append((
                enemy_center[0], enemy_center[1] - 50,  # 位置在敌人上方
                str(damage), 30, (255, 0, 0)  # 伤害值、显示时间、颜色
            ))

    # 添加获取日志的方法
    def get_battle_log(self, num_lines=3):
        return self.battle_log[-num_lines:] if len(self.battle_log) >= num_lines else self.battle_log
    # 添加绘制日志框的方法
    def _draw_battle_log(self):
        # 创建灰底透明的日志框背景
        log_box_surface = pygame.Surface((self.log_box_width, self.log_box_height), pygame.SRCALPHA)
        log_box_surface.fill((50, 50, 50, 180))  # 灰色半透明背景
        self.screen.blit(log_box_surface, (self.log_box_x, self.log_box_y))
        # 绘制日志文本
        logs = self.get_battle_log(5)  # 获取最近5条日志
        for i, log in enumerate(logs):
            if log:  # 只显示非空日志
                text_surface = self.log_font.render(log, True, (255, 255, 255))  # 白色文字
                text_y = self.log_box_y + 10 + i * self.log_line_height
                self.screen.blit(text_surface, (self.log_box_x + 10, text_y))

    def _draw_status_bars(self):
        """绘制血条（跟随角色上方）"""
        bar_width, bar_height = self.status_bar_size
        name_font = self.settings.font_menu
        bar_font = self.settings.font_small

        # 角色位置（用于定位血条）
        player_center = self._get_player_center()
        enemy_center = self._get_enemy_center()

        # 主角血条（角色上方）
        player_name_text = name_font.render(self.player.name, True, self.settings.color_white)
        player_name_rect = player_name_text.get_rect(
            centerx=player_center[0],
            bottom=player_center[1] - self.player_image.get_height()//2 - 10  # 角色头顶上方10px
        )
        self.screen.blit(player_name_text, player_name_rect)

        # HP条在姓名下方
        player_hp_bg_rect = pygame.Rect(
            player_name_rect.centerx - bar_width//2,
            player_name_rect.bottom + 5,
            bar_width,
            bar_height
        )
        pygame.draw.rect(self.screen, (0, 0, 0), player_hp_bg_rect, 2, border_radius=3)  # 黑边框
        pygame.draw.rect(self.screen, (200, 200, 200), player_hp_bg_rect.inflate(-4, -4), border_radius=2)  # 灰色背景
        hp_percent = max(0, self.player.current_hp / self.player.max_hp)
        player_hp_fg_rect = player_hp_bg_rect.inflate(-4, -4).copy()
        player_hp_fg_rect.width = int(bar_width * hp_percent)
        pygame.draw.rect(self.screen, (255, 0, 0), player_hp_fg_rect, border_radius=2)  # 红色HP
        player_hp_text = bar_font.render(f"HP {int(self.player.current_hp)}/{int(self.player.max_hp)}", True, (255, 255, 255))
        self.screen.blit(player_hp_text, player_hp_text.get_rect(center=player_hp_bg_rect.center))

        # 敌人血条（角色上方）
        enemy_name_text = name_font.render(self.enemy.name, True, self.settings.color_white)
        enemy_name_rect = enemy_name_text.get_rect(
            centerx=enemy_center[0],
            bottom=enemy_center[1] - self.enemy_image.get_height()//2 - 10  # 角色头顶上方10px
        )
        self.screen.blit(enemy_name_text, enemy_name_rect)

        # HP条在姓名下方
        enemy_hp_bg_rect = pygame.Rect(
            enemy_name_rect.centerx - bar_width//2,
            enemy_name_rect.bottom + 5,
            bar_width,
            bar_height
        )
        pygame.draw.rect(self.screen, (0, 0, 0), enemy_hp_bg_rect, 2, border_radius=3)
        pygame.draw.rect(self.screen, (200, 200, 200), enemy_hp_bg_rect.inflate(-4, -4), border_radius=2)
        enemy_hp_percent = max(0, self.enemy.current_hp / self.enemy.max_hp)
        enemy_hp_fg_rect = enemy_hp_bg_rect.inflate(-4, -4).copy()
        enemy_hp_fg_rect.width = int(bar_width * enemy_hp_percent)
        pygame.draw.rect(self.screen, (255, 0, 0), enemy_hp_fg_rect, border_radius=2)
        enemy_hp_text = bar_font.render(f"HP {int(self.enemy.current_hp)}/{int(self.enemy.max_hp)}", True, (255, 255, 255))
        self.screen.blit(enemy_hp_text, enemy_hp_text.get_rect(center=enemy_hp_bg_rect.center))

    def _get_player_center(self):
        """获取主角中心坐标（屏幕中心偏左）"""
        center_x = self.settings.screen_width // 2 - self.role_center_offset
        center_y = self.settings.screen_height // 2 - 50  # 居中偏上
        return (center_x, center_y)

    def _get_enemy_center(self):
        """获取敌人中心坐标（屏幕中心偏右）"""
        center_x = self.settings.screen_width // 2 + self.role_center_offset
        center_y = self.settings.screen_height // 2 - 50  # 与主角对称
        return (center_x, center_y)

    def _update_shake_effect(self):
        """更新震动效果和受击特效计时器"""
        # 更新震动效果
        if self.shake_count > 0:
            self.shake_count -= 1
        else:
            self.player_shake = False
            self.enemy_shake = False
        
        # 更新受击特效计时器
        if self.player_hit_timer > 0:
            self.player_hit_timer -= 1
        else:
            self.player_hit = False
        
        if self.enemy_hit_timer > 0:
            self.enemy_hit_timer -= 1
        else:
            self.enemy_hit = False
            
        # 更新闪烁效果计时器
        if self.player_flash_timer > 0:
            self.player_flash_timer -= 1
        else:
            self.player_flash = False
            
        if self.enemy_flash_timer > 0:
            self.enemy_flash_timer -= 1
        else:
            self.enemy_flash = False
            
        # 更新伤害数字
        self.damage_numbers = [
            (x, y - 1, text, timer - 1, color) 
            for x, y, text, timer, color in self.damage_numbers 
            if timer > 0
        ]

    def handle_events(self):
        """事件处理"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            for btn in self.skill_buttons:
                btn.handle_event(event)

    def draw(self):
        """绘制所有元素"""
        # 1. 绘制战斗主背景
        self.screen.blit(self.background, (0, 0))

        # 新增：绘制战斗日志框
        self._draw_battle_log()

        # 2. 绘制角色（中心对称分布）
        # 主角
        player_center = self._get_player_center()
        player_img_rect = self.player_image.get_rect(center=player_center)
        
        # 计算主角震动偏移 - 使用强度序列使震动更自然
        if self.player_shake and self.shake_count < len(self.shake_intensity):
            intensity = self.shake_intensity[self.shake_count]
            player_offset_x = random.randint(-intensity, intensity)
            player_offset_y = random.randint(-intensity, intensity)
        else:
            player_offset_x = 0
            player_offset_y = 0
        
        # 处理主角透明闪烁效果
        if self.player_flash and (self.player_flash_timer // self.flash_interval) % 2 == 0:
            # 创建临时表面用于透明度调整
            temp_player_img = self.player_image.copy()
            temp_player_img.set_alpha(self.flash_alpha)  # 设置透明度
            self.screen.blit(
                temp_player_img,
                (player_img_rect.x + player_offset_x, player_img_rect.y + player_offset_y)
            )
        else:
            # 正常绘制
            self.screen.blit(
                self.player_image,
                (player_img_rect.x + player_offset_x, player_img_rect.y + player_offset_y)
            )

        # 敌人
        enemy_center = self._get_enemy_center()
        enemy_img_rect = self.enemy_image.get_rect(center=enemy_center)
        
        # 计算敌人震动偏移（使用敌人专用震动强度）
        if self.enemy_shake and self.shake_count < len(self.enemy_shake_intensity):
            intensity = self.enemy_shake_intensity[self.shake_count]
            enemy_offset_x = random.randint(-intensity, intensity)
            enemy_offset_y = random.randint(-intensity, intensity)
        else:
            enemy_offset_x = 0
            enemy_offset_y = 0
        
        # 处理敌人透明闪烁效果
        if self.enemy_flash and (self.enemy_flash_timer // self.flash_interval) % 2 == 0:
            # 创建临时表面用于透明度调整
            temp_enemy_img = self.enemy_image.copy()
            temp_enemy_img.set_alpha(self.flash_alpha)  # 设置透明度
            self.screen.blit(
                temp_enemy_img,
                (enemy_img_rect.x + enemy_offset_x, enemy_img_rect.y + enemy_offset_y)
            )
        else:
            # 正常绘制
            self.screen.blit(
                self.enemy_image,
                (enemy_img_rect.x + enemy_offset_x, enemy_img_rect.y + enemy_offset_y)
            )

        # 3. 绘制受击特效（增强主角受击效果显示）
        if self.player_hit:
            # 计算受击特效位置（与角色中心对齐）
            hit_rect = self.hit_effect_image.get_rect(center=player_center)
            # 受击特效随角色震动
            self.screen.blit(
                self.hit_effect_image, 
                (hit_rect.x + player_offset_x, hit_rect.y + player_offset_y)
            )
            
        if self.enemy_hit:
            hit_rect = self.hit_effect_image.get_rect(center=enemy_center)
            # 受击特效随角色震动
            self.screen.blit(
                self.hit_effect_image, 
                (hit_rect.x + enemy_offset_x, hit_rect.y + enemy_offset_y)
            )

        # 4. 绘制伤害数字
        damage_font = pygame.font.SysFont("SimHei", 24, bold=True)
        for x, y, text, timer, color in self.damage_numbers:
            # 伤害数字随时间变淡
            alpha = int(255 * (timer / 30))
            text_surf = damage_font.render(text, True, color)
            text_surf.set_alpha(alpha)
            text_rect = text_surf.get_rect(center=(x, y))
            self.screen.blit(text_surf, text_rect)

        # 5. 绘制底部技能区背景
        self.screen.blit(self.bottom_bg_image, (0, self.settings.screen_height - self.skill_area_height))

        # 6. 绘制血条（跟随角色）
        self._draw_status_bars()

        # 7. 绘制技能按钮
        for btn in self.skill_buttons:
            btn.draw(self.screen)

        # 更新屏幕
        pygame.display.flip()

    def run(self):
        """主循环"""
        clock = pygame.time.Clock()
        self.music_player.stop_music()
        while self.running:
            clock.tick(self.settings.fps)
            self.handle_events()
            self._update_shake_effect()
            self.music_player.play_music("battle")
            self.draw()
            
            # 检查战斗是否结束
            if self.battle.is_battle_over:
                # 根据获胜者显示相应弹窗
                winner = "player" if self.battle.winner == self.player else "enemy"
                popup = BattlePopup(self.settings, winner, self.screen)
                popup.run()  # 运行弹窗循环
                self.running = False  # 弹窗关闭后才退出战斗循环
        


# 测试代码
if __name__ == "__main__":
    class Skill:
        def __init__(self, name, max_pp, current_pp=0, skill_attack=0, attribute=""):
            self.name = name
            self.max_pp = max_pp
            self.current_pp = current_pp if current_pp != 0 else max_pp
            self.skill_attack = skill_attack
            self.attribute = attribute

    class TestChampion:
        def __init__(self, name, hp, max_hp, mp, max_mp, image_path, skills_deck):
            self.name = name
            self.hp = hp
            self.max_hp = max_hp
            self.mp = mp
            self.max_mp = max_mp
            self.image_path = image_path
            self.skills_deck = skills_deck
            self.current_hp = hp  # 添加当前生命值属性

    class TestCharacter(TestChampion):
        def __init__(self, name, hp, max_hp, mp, max_mp, image_path, skills_deck, attribute="", equipment_deck=None):
            super().__init__(name, hp, max_hp, mp, max_mp, image_path, skills_deck)
            self.attribute = attribute
            self.equipment_deck = equipment_deck if equipment_deck else []

    # 测试用战斗类
    class TestBattle:
        def __init__(self):
            self.battle_log = []
            self.is_battle_over = False
            self.winner = None
            
        def player_turn(self, action, skill_index):
            self.battle_log.append("玩家使用了技能，造成了20点伤害")
            return True
            
        def enemy_turn(self):
            self.battle_log.append("敌人使用了技能，造成了15点伤害")
            return True
            
        def end_battle(self, winner):
            pass

    # 测试数据
    test_skills = [
        Skill("water", 10, skill_attack=20, attribute="水"),
        Skill("rush", 20, skill_attack=15, attribute="普通"),
        Skill("seeing", 30, skill_attack=0, attribute="普通"),
        Skill("fast moving", 20, skill_attack=0, attribute="超能")
    ]
    test_player = TestCharacter(
        name="changan",
        hp=300.0, max_hp=300.0, mp=100.0, max_mp=100.0,
        image_path="image/test_charactor.png", skills_deck=test_skills, attribute="fire"
    )
    test_enemy = TestChampion(
        name="badguy",
        hp=250.0, max_hp=250.0, mp=80.0, max_mp=80.0,
        image_path="image/test_charactor.png", skills_deck=test_skills
    )

    # 创建战斗UI实例并运行
    battle = TestBattle()
    battle_ui = BattleUI(test_player, test_enemy, battle)
    battle_ui.run()